﻿using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.Runtime.Caching;
using Castle.Components.DictionaryAdapter;
using DHJ.Cost.Timing;
using System.Threading.Tasks;

namespace DHJ.Cost.Excel.Cache
{
    public class ExcelDataCache : IExcelDataCache, ISingletonDependency
    {
        private readonly ICacheManager _cacheManager;

        public ExcelDataCache(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        public async Task<ExcelDataCacheItem> GetCacheItemOrNull(string id)
        {
            return await _cacheManager
                .GetCache(ExcelDataCacheItem.CacheName)
                .GetOrDefaultAsync<string, ExcelDataCacheItem>(id);
        }

        public async Task ClearCacheItem(string id)
        {
            await _cacheManager
                .GetCache(ExcelDataCacheItem.CacheName).RemoveAsync(id);
        }


        public async Task AddExcelBatch(string id, string title, ExcelType type, OccurrenceTime time, ExcelBatchData batch)
        {
            var item = _cacheManager
                .GetCache(ExcelDataCacheItem.CacheName)
                .Get<string, ExcelDataCacheItem>(id, f => GetExcelDataCacheItemInternal(id, title, type, time));

            item.Batches.Add(batch);

            await _cacheManager.GetCache(ExcelDataCacheItem.CacheName).SetAsync(id, item);
        }


        [UnitOfWork]
        protected ExcelDataCacheItem GetExcelDataCacheItemInternal(string id, string title, ExcelType type, OccurrenceTime time)
        {
            return new ExcelDataCacheItem()
            {
                Id = id,
                Time = time,
                ExcelTitle = title,
                ExcelType = type,
                Batches = new EditableList<ExcelBatchData>()
            };
        }
    }
}
